package e2q.security.web.util;

import java.beans.PropertyEditorSupport;
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;

import e2q.web.orm.ICommonDao;

public class CommonEditor extends PropertyEditorSupport {
	ICommonDao dao;
    @SuppressWarnings("unchecked")
	Class cls;
    String idPropertyName;
    
	@SuppressWarnings("unchecked")
	public CommonEditor(ICommonDao dao,Class cls,String idPropertyName)
	{
		this.dao=dao;
        this.cls=cls;
        this.idPropertyName=idPropertyName;
	}
	public String getAsText()
	{
		Object obj = getValue();
		try {
            return (obj == null ? "" : BeanUtils.getProperty(obj,idPropertyName));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return "";
	}

	public void setAsText(String text) throws NumberFormatException
	{
		if (text != null && !text.equals(""))
		{
			try {
				setValue(dao.load(cls, new Long(text)));
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		else
		{
			setValue(null);
		}
	}
}
